package com.quectel.cms.controller.dept;


import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import cn.hutool.core.util.DesensitizedUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.ex.dept.DeptPersonException;
import com.quectel.cms.util.SessionHolder;
import com.quectel.cms.vo.dept.DeptPersonChangeDeptVo;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.constant.sys.SysConfigKeyConstants;
import com.quectel.core.module.dept.dto.DeptDto;
import com.quectel.core.module.dept.dto.DeptPersonDto;
import com.quectel.core.module.dept.service.DeptPersonService;
import com.quectel.core.module.dept.service.DeptService;
import com.quectel.core.module.scheduling.dto.SchedulingAttendanceGroupPersonBindingDto;
import com.quectel.core.module.scheduling.service.SchedulingAttendanceGroupPersonBindingService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.sys.module.sys.service.SysConfigService;
import com.quectel.util.common.*;
import com.quectel.util.http.HttpRestUtils;
import com.quectel.util.security.RandomHeaderSignUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2022/03/24 10:07
 */
@RestController
@RequestMapping("deptPerson")
@Tag(name = "DeptPersonController", description = "部门人员相关api")
public class DeptPersonController extends BaseController {

    @DubboReference
    private DeptPersonService deptPersonService;
    @DubboReference
    private SchedulingAttendanceGroupPersonBindingService groupPersonBindingService;
    @DubboReference
    private DeptService deptService;
    @DubboReference
    private VillageService villageService;
    @DubboReference
    private SysConfigService sysConfigService;

    private static final HttpRestUtils HTTP_REST_UTILS = HttpRestUtils.getDefaultInstance();

    @GetMapping("listWithoutChecked")
    @RequirePermissions(values = "deptPerson:list")
    @Operation(summary = "查询员工列表，不包含已经被其他考勤组选中的人员")
    public Response<Page<DeptPersonDto>> listWithoutChecked(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest))
                .like(LambdaUtil.getFieldName(DeptPersonDto::getName))
                .like(LambdaUtil.getFieldName(DeptPersonDto::getMobile));

        String groupId = String.valueOf(request.getParams().get("groupId"));

        // 查询非当前组的人员id ,下方查询全部人员，进行过滤剔除，避免选中已绑定的其他组的人员
        Map<String,Object> queryMap = new HashMap<>();
        queryMap.put("villageId", request.getParams().get("villageId"));
        if (StringUtils.isNotEmpty(groupId)){
            queryMap.put("eliminateId",groupId);
        }
        List<SchedulingAttendanceGroupPersonBindingDto> groupPersonBindingDtos = groupPersonBindingService.queryList(queryMap);
        List<Long> deptPersonIds = groupPersonBindingDtos.stream()
                .map(SchedulingAttendanceGroupPersonBindingDto::getPersonId).collect(Collectors.toList());


        super.fillAuthorityData(request.getParams());
        request.put(LambdaUtil.getFieldName(DeptPersonDto::getStatus), SystemConstants.YES);

        int total = deptPersonService.queryTotal(request.getParams());

        List<DeptPersonDto> list = null;
        if (total > 0) {
            list = deptPersonService.queryList(request.getParams());
            list.removeIf(dto -> deptPersonIds.contains(dto.getId()));
        } else {
            list = new ArrayList<>();
        }

        Page<DeptPersonDto> page = new Page<>(0,0,0,new ArrayList<>());

        if (CollectionUtils.isEmpty(list)){
            page = new Page<>(request.getPageNo(), request.getPageSize(), 0, list);
        }else {
            page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        }

        return Response.<Page<DeptPersonDto>>ok().wrap(page);
    }

    /**
     * 列表
     */
    @GetMapping("queryByVillageId")
    @Operation(summary = "根据小区id查询部门人员列表")
    public Response<List<DeptPersonDto>> list(
            @RequestParam Long villageId
    ) {
        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(LambdaUtil.getFieldName(DeptPersonDto::getStatus), SystemConstants.YES);
        params.put(LambdaUtil.getFieldName(DeptPersonDto::getVillageId), String.valueOf(villageId));

        List<DeptPersonDto> list = deptPersonService.queryList(params);

        return Response.<List<DeptPersonDto>>ok().wrap(list);
    }

    /**
     * 列表
     */
    @GetMapping("queryAll")
    @Operation(summary = "查询部门人员列表")
    public Response<List<DeptPersonDto>> list(
    ) {
        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        List<DeptPersonDto> list = deptPersonService.queryList(params);
        return Response.<List<DeptPersonDto>>ok().wrap(list);
    }


    /**
     * 列表
     */
    @PostMapping("importExcel")
    @RequirePermissions(values = "deptPerson:importExcel")
    @Operation(summary = "导入人员信息")
    public Response<Object> importExcel(
            MultipartHttpServletRequest request
    ) {

        Iterator<String> fileNames = request.getFileNames();
        while (fileNames.hasNext()) {
            String next = fileNames.next();
            List<MultipartFile> files = request.getFiles(next);
            for (MultipartFile file : files) {
                int successPerson = 0;
                int total = 0;
                try {
                    //校验楼栋数据合法性
                    List<Map<Integer, String>> analysis = POIUtils.analysis(file.getInputStream(), 1, 0);

                    for (Map<Integer, String> map : analysis) {
                        total++;
                        try {
                            String villageName = map.get(12);
                            VillageDto villageDto = villageService.selectByName(SessionHolder.getSysUser().getTenantId(), villageName);
                            if (villageDto == null) {
                                continue;
                            }
                            DeptDto deptDto = deptService.selectByName(villageDto.getId(), map.get(13));
                            if (deptDto == null) {
                                continue;
                            }
                            String mobile = map.get(2);
                            DeptPersonDto dbValue = deptPersonService.selectByVillageAndMobile(villageDto.getId(), mobile);
                            if (dbValue != null) {
                                continue;
                            }

                            DeptPersonDto personDto = new DeptPersonDto();
                            fillSaveCommonData(personDto);
                            personDto.setVillageId(villageDto.getId());
                            personDto.setDeptId(deptDto.getId());
                            personDto.setJobNo(map.get(0));
                            personDto.setName(map.get(1));
                            personDto.setMobile(mobile);
                            personDto.setEmail(map.get(3));
                            personDto.setPost(map.get(4));
                            personDto.setGender(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.GENDER, map.get(5), Byte.class));
                            personDto.setJoinedDate(DateUtils.parse(map.get(6), DateUtils.FormatType.SIMPLE));
                            personDto.setFirstJobDate(DateUtils.parse(map.get(7), DateUtils.FormatType.SIMPLE));
                            personDto.setCardType(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.CARD_TYPE, map.get(8), Byte.class));
                            personDto.setCardNo(map.get(9));
                            personDto.setStatus(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.COMMON_STATUS, map.get(10), Byte.class));
                            personDto.setIsAdmin(SysCodeUtils.easyToGetValue(SysCodeKeyConstants.YES_OR_NOT, map.get(11), Byte.class));

                            deptPersonService.save(personDto);
                            successPerson++;
                        } catch (Exception e) {
                            logger.error("解析某个人员信息出错", e);
                            continue;
                        }

                    }
                    return Response.customize(Response.getSUCCESS_CODE(), "导入人员数:" + successPerson + " 总条数:" + total);
                } catch (Exception e) {
                    logger.error("解析楼栋信息出错");
                }
            }
        }
        return Response.error("导入数据出错");
    }


    /**
     * 列表
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "deptPerson:exportExcel")
    @Operation(summary = "导出部门人员")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(params)
                .like(LambdaUtil.getFieldName(DeptPersonDto::getName))
                .like(LambdaUtil.getFieldName(DeptPersonDto::getMobile));
        ;

        super.fillAuthorityData(params);

        List<DeptPersonDto> result = new ArrayList<>();
        int pageNo = 0;
        params.put("limit", 1000);
        while (true) {
            params.put("offset", pageNo++ * 1000);
            List<DeptPersonDto> list = deptPersonService.queryList(params);
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                break;
            }
            result.addAll(list);
            if (list.size() < 1000) {
                break;
            }
        }
        String[] headers = new String[]{"工号", "姓名", "手机号", "邮箱", "入职日期", "首次参加工作日期", "证件类型", "证件号", "岗位", "性别", "所属社区", "归属部门"};

        List<String[]> dataList = new ArrayList<>();
        for (DeptPersonDto data : result) {

            // 脱敏
//            data.setName(DesensitizedUtil.chineseName(data.getName()));
//            data.setMobile(DesensitizedUtil.mobilePhone(data.getMobile()));
//            data.setCardNo(DesensitizedUtil.idCardNum(data.getCardNo(), 2, 2));

            String[] item = new String[headers.length];
            item[0] = data.getJobNo();
            item[1] = DesensitizedUtil.chineseName(data.getName());
            item[2] = DesensitizedUtil.mobilePhone(data.getMobile());
            item[3] = data.getEmail();
            item[4] = data.getJoinedDate()!=null?DateUtils.format(data.getJoinedDate(), DateUtils.FormatType.SIMPLE):"";
            item[5] = data.getFirstJobDate()!=null?DateUtils.format(data.getFirstJobDate(), DateUtils.FormatType.SIMPLE):"";
            item[6] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.CARD_TYPE, data.getCardType() + "");
            item[7] = DesensitizedUtil.idCardNum(data.getCardNo(), 2, 2);
            item[8] = data.getPost();
            item[9] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.GENDER, data.getGender() + "");
            item[10] = data.getVillageName();
            item[11] = data.getDept() != null ? data.getDept().getName() : null;
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "社区人员信息", headers, dataList, "社区人员信息");
    }

    /**
     * 变更人员部门
     */
    @PostMapping("changeDept")
    @RequirePermissions(values = "deptPerson:changeDept")
    @Operation(summary = "变更人员部门")
    public Response<Object> changeDept(
            @RequestBody DeptPersonChangeDeptVo deptPersonChangeDeptVo
    ) {
        DeptDto deptDto = deptService.selectById(deptPersonChangeDeptVo.getChangeDeptId());

        for (DeptPersonDto deptPersonDto : deptPersonChangeDeptVo.getDeptPersonDtoList()) {
            if (!Objects.equals(deptDto.getVillageId(), deptPersonDto.getVillageId())) {
                return Response.error("非法的数据注入");
            }
            DeptPersonDto updateObj = new DeptPersonDto();
            updateObj.setId(deptPersonDto.getId());
            updateObj.setDeptId(deptDto.getId());
            deptPersonService.updateById(updateObj);
        }
        return Response.ok();
    }

    /**
     * 列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "deptPerson:list")
    @Operation(summary = "部门人员的分页查询列表")
    public Response<Page<DeptPersonDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest))
                .like(LambdaUtil.getFieldName(DeptPersonDto::getName))
                .like(LambdaUtil.getFieldName(DeptPersonDto::getMobile));

        super.fillAuthorityData(request.getParams());
        int total = deptPersonService.queryTotal(request.getParams());

        List<DeptPersonDto> list = null;
        if (total > 0) {
            list = deptPersonService.queryList(request.getParams());
//            for (DeptPersonDto deptPersonDto : list) {
            // 1221 跟程亮沟通取消脱敏
//                deptPersonDto.setName(DesensitizedUtil.chineseName(deptPersonDto.getName()));
//                deptPersonDto.setMobile(DesensitizedUtil.mobilePhone(deptPersonDto.getMobile()));
//                deptPersonDto.setCardNo(DesensitizedUtil.idCardNum(deptPersonDto.getCardNo(), 2, 2));
//            }
        } else {
            list = new ArrayList<>();
        }

        Page<DeptPersonDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<DeptPersonDto>>ok().wrap(page);
    }


    /**
     * 编辑反显查询
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "deptPerson:edit")
    @Operation(summary = "查询单条部门人员记录")
    public Response<DeptPersonDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (deptPersonService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        DeptPersonDto deptPersonDto = deptPersonService.selectById(id);

        return Response.<DeptPersonDto>ok().wrap((deptPersonDto));
    }

    /**
     * 信息
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "deptPerson:info")
    @Operation(summary = "查询单条部门人员记录")
    public Response<DeptPersonDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (deptPersonService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        DeptPersonDto deptPersonDto = deptPersonService.selectById(id);
//        if (deptPersonDto != null) {
        // 1221 跟程亮沟通取消脱敏
//                deptPersonDto.setName(DesensitizedUtil.chineseName(deptPersonDto.getName()));
//                deptPersonDto.setMobile(DesensitizedUtil.mobilePhone(deptPersonDto.getMobile()));
//                deptPersonDto.setCardNo(DesensitizedUtil.idCardNum(deptPersonDto.getCardNo(), 2, 2));
//        }

        return Response.<DeptPersonDto>ok().wrap(deptPersonDto);
    }

    /**
     * 保存
     */
    @PostMapping("save")
    @RequirePermissions(values = "deptPerson:edit")
    @Operation(summary = "保存单条部门人员记录")
    public Response<Object> save(@RequestBody @Validated DeptPersonDto deptPersonDto) {

        DeptPersonDto dbValue =
                deptPersonService.selectByVillageAndMobile(deptPersonDto.getVillageId(), deptPersonDto.getMobile());
        if (dbValue != null) {
            return Response.error("当前社区下已存在该手机号，不允许重复添加");
        }

        //填充基础数据
        fillSaveCommonData(deptPersonDto);

        deptPersonService.save(deptPersonDto);

        return Response.ok();
    }

    /**
     * 修改
     */
    @PostMapping("update")
    @RequirePermissions(values = "deptPerson:edit")
    @Operation(summary = "修改单条部门人员记录")
    public Response<Object> update(@RequestBody @Validated DeptPersonDto deptPersonDto) {


        DeptPersonDto dbValue =
                deptPersonService.selectByVillageAndMobile(deptPersonDto.getVillageId(), deptPersonDto.getMobile());
        if (dbValue != null && !Objects.equals(dbValue.getId(), deptPersonDto.getId())) {
            return Response.error("当前社区下已存在该手机号，不允许重复添加");
        }

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(deptPersonDto.getId()));
        if (deptPersonService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(deptPersonDto);

        deptPersonService.updateById(deptPersonDto);

        if (SystemConstants.ABNORMAL.equals(deptPersonDto.getStatus())) {
            //禁用员工登录 由于cms和emp系统不使用一套session持久化redis所以需要向emp发送冻结用户的请求
            sendDisableDeptPersonReq(Arrays.asList(deptPersonDto.getId()));
        }


        return Response.ok();
    }

    private void sendDisableDeptPersonReq(List<Long> ids) {
        try {
            //禁用员工登录 由于cms和emp系统不使用一套session持久化redis所以需要向emp发送冻结用户的请求
            String innerGatewayUrl = sysConfigService.getConfigValueByKey(SysConfigKeyConstants.GATEWAY_INNER_BASE_URL);
            String secret = sysConfigService.getConfigValueByKey(SysConfigKeyConstants.COMMON_SALT);
            String resp = HTTP_REST_UTILS.post(
                    innerGatewayUrl + SystemConstants.ApiPath.EMP_PATH.getPath() + "cms/command/disableDeptUser",
                    ids,
                    RandomHeaderSignUtils.sign(secret),
                    new TypeReference<String>() {
                    }
            ).getRight();
            logger.info("禁用用户从emp系统返回参数为:{}", resp);
        } catch (Exception e) {
            throw new DeptPersonException("Send disable dept user request error", e);
        }
    }

    /**
     * 删除
     */
    @PostMapping("delete")
    @RequirePermissions(values = "deptPerson:delete")
    @Operation(summary = "批量删除存在的部门人员记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (deptPersonService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }


        }
        //禁用员工登录 由于cms和emp系统不使用一套session持久化redis所以需要向emp发送冻结用户的请求
        sendDisableDeptPersonReq(ListUtil.toLinkedList(ids));

        deptPersonService.deleteBatch(ids);

        return Response.ok();
    }

    /**
     * 审批流穿梭框部门人员列表 名称不脱敏
     */
    @GetMapping("nonPagedlist")
    @RequirePermissions(values = "deptPerson:list")
    @Operation(summary = "部门人员查询不带分页列表")
    public Response<List<DeptPersonDto>> nonPagedlist() {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest))
                .like(LambdaUtil.getFieldName(DeptPersonDto::getName))
                .like(LambdaUtil.getFieldName(DeptPersonDto::getMobile));

        super.fillAuthorityData(request.getParams());
        int total = deptPersonService.queryTotal(request.getParams());

        List<DeptPersonDto> list = null;
        if (total > 0) {
            list = deptPersonService.queryList(request.getParams());
            for (DeptPersonDto deptPersonDto : list) {
                // 脱敏
                deptPersonDto.setMobile(DesensitizedUtil.mobilePhone(deptPersonDto.getMobile()));
                deptPersonDto.setCardNo(DesensitizedUtil.idCardNum(deptPersonDto.getCardNo(), 2, 2));
            }
        } else {
            list = new ArrayList<>();
        }
        return Response.<List<DeptPersonDto>>ok().wrap(list);
    }
}
